package org.mainlove.project.web.gen;

import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.mainlove.project.web.LabsServlet;
import org.mainlove.project.web.framework.result.ActionForward;

@SuppressWarnings("serial")
public class GenServlet extends LabsServlet {

	private static final Logger log = Logger.getLogger(GenServlet.class.getName());

   <#list g?keys as itemKey>
		<#assign item = g[itemKey]>
	private ${item.serviceClassName} ${item.serviceName} = new ${item.serviceClassName}();
   </#list>   

	@Override
	protected void dispathRequest(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String serviceName = getRequestServiceName(request);
		String method = request.getParameter("method");
		String methodWay = request.getMethod().toUpperCase();

		if (StringUtils.isBlank(serviceName) || StringUtils.isBlank(method)) {
			response.sendError(404);
		}

		ActionForward actionForward = null;
		JSONObject jsonObject = getRequestJsonObject(request, response);

   <#list g?keys as itemKey>
		<#assign item = g[itemKey]>
	   	if(("${itemKey}").equals(serviceName)) {
	   		<#list item.method as m>
	   		    if (checkMethod(method, methodWay, "${m.name}", "${m.methodWay}")) {
				actionForward = ${item.serviceName}.${m.methodName}(request, response, jsonObject);
			}
			<#if m_has_next>
	        else </#if>
	   		</#list>
	   		 else {
				log.warning(" no methodName=[" + method + "] for service"
						+ " ${item.serviceClassName}");
				response.sendError(404);
				return;
			}
	   	}
	    <#if itemKey_has_next>
	    else </#if>
	    </#list>   
        else {
			log.warning(" no serviceName=[" + serviceName + "] exist");
			response.sendError(404);
			return;
		}

		if (actionForward == null) {
			throw new Exception("actionForward should not be null -serviceName [" + serviceName
					+ "]-method[" + method + "]");
		}
		actionForward.responseResult(response);



		 

	}

}
